package com.mr.dao.service.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mr.constants.Tables;
import com.mr.dao.common.CommonDao;
import com.mr.dao.entity.customer.OrderedSubproduct;
import com.mr.dao.service.OrderedSubproductService;
import com.mr.dao.util.CriteriaUtil;

@Service
public class OrderedSubproductServiceImpl implements OrderedSubproductService {
	@Autowired
	protected CommonDao commonDao;

	@Override
	public List<OrderedSubproduct> findByCustomer(String[] names, Object[] values) {

		if (names == null || values == null || names.length != values.length) {
			return null;
		}
		Criteria criteria = CriteriaUtil.create(commonDao.getSession(), OrderedSubproduct.class);
		criteria.createAlias(Tables.ORDER, "co");
		criteria.createAlias("co." + Tables.CUSTOMER, "ca");
		for (int i = 0; i < names.length; i++) {
			criteria.add(Restrictions.eq("ca." + names[i], values[i]));
		}
		List<OrderedSubproduct> orderedSubproducts = CriteriaUtil.list(criteria);
		for (OrderedSubproduct orderedSubproduct : orderedSubproducts) {
			Hibernate.initialize(orderedSubproduct.getCustomer_order());
			Hibernate.initialize(orderedSubproduct.getCustomer_order().getCustomer_account());
			Hibernate.initialize(orderedSubproduct.getSubproduct());
			Hibernate.initialize(orderedSubproduct.getSubproduct().getProduct());
		}
		return orderedSubproducts;
	}

	@Override
	public List<OrderedSubproduct> findByCustomerEmail(String email) {
		return findByCustomer(new String[] { "user_email" }, new Object[] { email });
	}
}
